/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BancoInteiroFrame.java
 *
 * Created on 18/07/2010, 02:27:28
 */
package user_gui;

import elemento.ClienteTelefone;
import in_out.GeraRelatorio;
import java.io.File;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import op.Telefone;

/**
 *
 * @author Jônatas
 */
public class BancoInteiroFrame extends javax.swing.JFrame {

    /** Creates new form BancoInteiroFrame */
    public BancoInteiroFrame() {
        initComponents();
        try {
            fillTable();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Ocorreu um erro a consulta ao banco.");
            ex.printStackTrace();
            dispose();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Lista");
        setResizable(false);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Telefone", "Nome"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Gerar Relatório");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(308, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-439)/2, (screenSize.height-479)/2, 439, 479);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        File file = getFilePath();

        if (file == null) {
            return;
        }

        int columnCount = jTable1.getColumnCount();
        int rowCount = jTable1.getRowCount();

        String[] columnTitles = new String[columnCount];

        for (int i = 0; i < columnCount; i++) {
            columnTitles[i] = jTable1.getColumnName(i);
        }

        String[][] tableValues = new String[rowCount][columnCount];

        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < columnCount; j++) {

                tableValues[i][j] = jTable1.getValueAt(i, j).toString();

            }
        }

        try {
            GeraRelatorio.createSimpleReport(columnTitles, tableValues, file, "Itens do Banco");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Houve um problema na escrita do arquivo, por favor verifique se este"
                    + "arquivo não está sendo utilizado por outra aplicação.", "Erro", JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
            return;
        }

        JOptionPane.showMessageDialog(this, "O arquivo foi salvo com sucesso", "", JOptionPane.INFORMATION_MESSAGE);


    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    private void fillTable() throws Exception {
        List<ClienteTelefone> telefones = null;


        telefones = FramePrincipal.COMUNICABD.selectAll(FramePrincipal.tableName);

        if (telefones == null || telefones.isEmpty()) {
            return;
        }

        String[][] matrizTelefone = createTable(telefones);

        DefaultTableModel model = new DefaultTableModel(matrizTelefone, new String[]{
                    "Telefone", "Nome"
                }) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        jTable1.setModel(model);

    }

    public static String[][] createTable(List<ClienteTelefone> telefones) {

        String[][] matrizTelefone = new String[telefones.size()][2];

        Telefone tel = null;

        for (int i = 0; i < telefones.size(); i++) {
            String temp = telefones.get(i).getTelefone();

            if (temp.matches("[^0-9]")) {
                tel = new Telefone(temp, true);
            } else {
                tel = new Telefone(temp);
            }
            matrizTelefone[i][0] = tel.toString();
            matrizTelefone[i][1] = telefones.get(i).getNome();
        }

        return matrizTelefone;

    }

    private File getFilePath() {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }

                return f.getName().endsWith(".xls");
            }

            @Override
            public String getDescription() {
                return "*.xls";
            }
        });

        chooser.showSaveDialog(this);
        File file = chooser.getSelectedFile();

        if (file.exists()) {

            String[] options = {"Sim", "Não"};

            int ctz = JOptionPane.showOptionDialog(this, "Deseja sobrescrever o arquivo existente?", "Aviso",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);

            if (ctz != 0) {
                return null;
            }

        }

        String filePath = file.getAbsolutePath();
        if (!filePath.endsWith(".xls")) {
            filePath += ".xls";
        }

        return new File(filePath);

    }
}
